<?php
/**
 *  通过图片的media_id获取图片，并且保存到bos上，返回TencentAI 图片
 * Author: lyun
 * Date: 2018/5/11
 * Created by Panxsoft.
 */


namespace App\Http\Controllers\MayPromo;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Promo\PromoPicUrlRequest;
use App\Services\Image\Compress;
use App\Services\OpenWechat\AppFactory;
use App\Services\TenCentAI\TenCentAIService;
use App\Services\Utils\Bosable;
use EasyWeChat\Kernel\Http\StreamResponse;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;

class WechatImageController extends ApiController
{
    const COMPRESS_RATE = 0.9;       // 图片的压缩比率；

    const LIMIT_IMAGE_SIZE = 500000; // 腾讯ai限制图片的大小500kb

    public $bos_key_promo_img = 'wechat_promo_img/';  // 微信营销的图片

    use Bosable;

    /**
     *  返回 TencentAi 美妆的编码
     *
     * @return array|\Illuminate\Http\Response
     */
    public function create()
    {
        // 返回TencentAi美颜的编码图

        $cosmetics = [
            ['id'=>1, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/1.png', 'alt'=>'芭比粉'],
            ['id'=>2, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/2.png', 'alt'=>'清透'],
            ['id'=>3, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/3.png', 'alt'=>'烟灰'],
            ['id'=>4, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/4.png', 'alt'=>'自然'],
            ['id'=>5, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/5.png', 'alt'=>'樱花粉'],
            ['id'=>6, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/6.png', 'alt'=>'原宿红'],
            ['id'=>7, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/7.png', 'alt'=>'闪亮'],
            ['id'=>8, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/8.png', 'alt'=>'粉紫'],
//            ['id'=>9, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/9.png', 'alt'=>'韩妆 - 粉嫩'],
//            ['id'=>10, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/10.png', 'alt'=>'韩妆 - 自然'],
//            ['id'=>11, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/11.png', 'alt'=>'韩妆 - 清透'],
//            ['id'=>12, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/12.png', 'alt'=>'韩妆 - 大地色'],
//            ['id'=>13, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/13.png', 'alt'=>'韩妆 - 玫瑰'],
//            ['id'=>14, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/14.png', 'alt'=>'裸妆 - 自然'],
//            ['id'=>15, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/15.png', 'alt'=>'裸妆 - 清透'],
//            ['id'=>16, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/16.png', 'alt'=>'裸妆 - 桃粉'],
//            ['id'=>17, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/17.png', 'alt'=>'裸妆 - 橘粉'],
//            ['id'=>18, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/18.png', 'alt'=>'裸妆 - 春夏'],
//            ['id'=>19, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/19.png', 'alt'=>'裸妆 - 秋冬'],
//            ['id'=>20, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/20.png', 'alt'=>'主题妆 - 经典复古'],
//            ['id'=>21, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/21.png', 'alt'=>'主题妆 - 性感混血'],
//            ['id'=>22, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/22.png', 'alt'=>'主题妆 - 炫彩明眸'],
//            ['id'=>23, 'src'=>'https://yyb.gtimg.com/aiplat/ai/upload/doc/facecosmetic/23.png', 'alt'=>'主题妆 - 紫色魅惑'],
        ];

        return $this->response(compact('cosmetics'));
    }

    /**
     *  用media_id获取图片，上传到百度云，返回url地址，TencentAI美妆，返回base64
     *
     * @param PromoPicUrlRequest $request
     * @return array|\Illuminate\Http\Response|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function getPicUrlByMediaId(PromoPicUrlRequest $request)
    {
        $bos_url = $request->bos_url;

        if ($bos_url) {

            $tencent_image = (new TenCentAIService)->ptuFaceCosmetic($bos_url, $request->id);

        } else {

            $app = (new AppFactory())->authorizerApp($request->appid);

            /** @var StreamResponse $stream */
            $stream = $app->media->get($request->media_id);

            $bos_url = $this->uploadPicToBos($stream);

            $tencent_image = (new TenCentAIService)->ptuFaceCosmetic($bos_url, $request->id);

        }

        return $this->response(compact('tencent_image', 'bos_url'));
    }

    /**
     * @param StreamResponse $stream
     * @return string
     */
    private function uploadPicToBos(StreamResponse $stream)
    {
        $contents = $stream->getBody()->getContents();

        $hash = time();
        $path = storage_path("may_promo_wx_img_{$hash}.jpg");

        file_put_contents($path, $contents);

        // 压缩图片到500KB
        $this->compressImage($path);

        $bos_key = $this->uploadFile($path, $this->bos_key_promo_img);

        $bos_url = $this->getStaticUrl($bos_key);

        @unlink($path);

        return $bos_url;
    }

    /**
     *  压缩图片到500kb
     *
     * @param $path
     */
    private function compressImage($path)
    {
        $image_size = getImageSize($path);

        $image_x = $image_size[0];

        if (fileSize($path) > self::LIMIT_IMAGE_SIZE) {

            Compress::handle($path, $image_x*self::COMPRESS_RATE);

            if (fileSize($path) > self::LIMIT_IMAGE_SIZE) $this->compressImage($path);
        }
    }

    /**
     * 测试公众号上传图片到微信，获取media_id
     *
     * @param Request $request
     * @return string
     */
    public function uploadTempImage(Request $request)
    {
        $upload_temp_path = $request->file('image')->getRealPath();

        /** @var \EasyWeChat\OpenPlatform\Authorizer\OfficialAccount\Application $app */
        $app = (new AppFactory())->authorizerApp($request->appid);

        $temp_img = storage_path('tmp_img.jpg');

        copy($upload_temp_path, $temp_img);

        $material_id = $app->media->uploadImage($temp_img);

        @unlink($temp_img);

        return $material_id;
    }

    /**
     * （测试用的）
     * 直接上传图片, tencentAI返回美妆的base64图片
     *
     * @param Request $request
     * @return array|\Illuminate\Http\Response
     */
    public function getPicUrlByPostFile(Request $request)
    {
        /** @var UploadedFile|string $image */
        $image = $request->image;

        if (is_file($image)) {
            $tencent_image = (new TenCentAIService)->ptuFaceCosmetic($image->getPathname(), $request->id);
            $image = $image->getPathname();
        } else {
            $tencent_image = (new TenCentAIService)->ptuFaceCosmetic($image, $request->id);
        }

        return $this->response(compact('tencent_image', 'image'));
    }

}